/**
 * Copyright (c) 2018, dreamkaylee@foxmail.com All Rights Reserved.
 */

package com.common.web;

import java.util.Date;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.common.filter.StringEscapeEditor;
import com.common.interceptor.DateConvertEditor;
import com.common.model.AjaxJson;
import com.common.shiro.bean.UserModel;

/**
 * 基础控制器
 * @author limk
 * @date 2018年2月14日 下午5:14:10
 * @version 1.0
 */
@Component
public class BaseController {

	/**
	 * 因为是单例模式，这样做很合理
	 */
	protected Logger logger = LogManager.getLogger(getClass());
	
	@InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
        /**
         * 自动转换日期类型的字段格式
         */
		binder.registerCustomEditor(Date.class, new DateConvertEditor());
        /**
         * 防止XSS攻击
         */
        binder.registerCustomEditor(String.class, new StringEscapeEditor());
    }
	
    /**
     * 获取当前登录用户对象
     * @return
     */
    public UserModel getUserModel() {
        return (UserModel) SecurityUtils.getSubject().getPrincipal();
    }

    /**
     * 判断当前用户是否已通过认证
     * @return
     */
	public static boolean hasAuthenticated() {
		return SecurityUtils.getSubject().isAuthenticated();
	}
    
	/**
	 * ajax失败
	 * @param msg 失败的消息
	 * @return
	 */
    public Object error(String msg) {
        AjaxJson aj = new AjaxJson();
        aj.setMsg(msg);
        return aj;
    }

    /**
     * ajax成功
     * @return
     */
    public Object success() {
        AjaxJson aj = new AjaxJson();
        aj.setSuccess(true);
        return aj;
    }

    /**
     * ajax成功
     * @param msg 消息
     * @return
     */
    public Object success(String msg) {
        AjaxJson aj = new AjaxJson();
        aj.setSuccess(true);
        aj.setMsg(msg);
        return aj;
    }

    /**
     * ajax成功
     * @param obj 成功时的对象
     * @return
     */
    public Object success(Object obj) {
        AjaxJson aj = new AjaxJson();
        aj.setSuccess(true);
        aj.setData(obj);
        return aj;
    }
    
}
